import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

// 交接班：开班/结班、现金盘点、期间销售统计（简化版）
export const useShiftStore = defineStore('shift', () => {
  const STORAGE_KEY = 'erppos_shifts'
  const CURRENT_KEY = 'erppos_shift_current'
  const shifts = ref([])
  const currentShift = ref(null)

  const isOpen = computed(() => !!currentShift.value)

  const persist = () => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(shifts.value))
    localStorage.setItem(CURRENT_KEY, JSON.stringify(currentShift.value))
  }

  const openShift = ({ operator, openingCash }) => {
    if (currentShift.value) return false
    const now = new Date()
    currentShift.value = {
      id: 'S' + now.getTime(),
      operator,
      openingCash: Number(openingCash || 0),
      startTime: now.toISOString(),
      closingCash: null,
      endTime: null,
      notes: '',
      stats: { salesQty: 0, salesAmount: 0 },
    }
    persist()
    return true
  }

  const closeShift = ({ closingCash, notes, salesQty = 0, salesAmount = 0 }) => {
    if (!currentShift.value) return false
    const now = new Date()
    currentShift.value.closingCash = Number(closingCash || 0)
    currentShift.value.endTime = now.toISOString()
    currentShift.value.notes = notes || ''
    currentShift.value.stats = { salesQty, salesAmount }
    shifts.value.unshift(currentShift.value)
    currentShift.value = null
    persist()
    return true
  }

  const initializeShifts = () => {
    const cached = localStorage.getItem(STORAGE_KEY)
    const cachedCurrent = localStorage.getItem(CURRENT_KEY)
    if (cached) shifts.value = JSON.parse(cached)
    if (cachedCurrent) currentShift.value = JSON.parse(cachedCurrent)
  }

  return {
    shifts,
    currentShift,
    isOpen,
    openShift,
    closeShift,
    initializeShifts,
  }
})


